<template>
  <!-- 加载状态 -->
  <LoadingSpinner v-if="isInitialLoading" />

  <!-- 主要内容 -->
  <PageLayout 
    v-else
    title="搜索结果" 
    :description="`搜索关键词：${searchQuery}`"
  >
    <!-- 使用通用筛选器组件 -->
    <div class="max-w-6xl w-full mx-auto relative z-30">
      <MovieFilterList
        :movies="filteredAndSortedMovies"
        :is-loading="isSearching"
        :has-more="hasMore"
        :extra-info="`关键词: ${searchQuery}`"
        :initial-filters="filters"
        :initial-sort="currentSort"
        :sort-options="sortOptions"
        :empty-state-title="hasActiveFilters ? '暂无符合条件的电影' : '未找到相关电影'"
        :empty-state-description="hasActiveFilters ? '请尝试调整筛选条件' : '尝试使用不同的关键词或调整筛选条件'"
        @update:filters="handleFiltersUpdate"
        @update:sort="handleSortUpdate"
        @load-more="loadMore"
        @clear-filters="clearFilters"
      />
    </div>
  </PageLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSearch } from '../composables/useSearch'
import { MovieFilterList } from '../components/movie'
import { LoadingSpinner } from '../components/ui'
import PageLayout from '../components/layout/PageLayout.vue'

const router = useRouter()
const route = useRoute()
const { performSearch, searchResults, isSearching } = useSearch()

// 响应式数据
const isInitialLoading = ref(true)
const currentPage = ref(0)
const pageSize = 20

// 搜索查询
const searchQuery = computed(() => route.query.q as string || '')

// 排序选项
const sortOptions = [
  { key: 'relevance', label: '相关度', icon: '🎯' },
  { key: 'views', label: '播放量', icon: '👁️' },
  { key: 'updated_at', label: '最新更新', icon: '🕒' },
  { key: 'year', label: '上映年份', icon: '📅' },
  { key: 'rating', label: '评分最高', icon: '⭐' }
]

const currentSort = ref('relevance')

// 筛选状态
const filters = ref({
  genre: 'all',
  universe: 'all',
  language: 'all',
  country: 'all',
  ai: 'all'
})

// 计算属性
const hasActiveFilters = computed(() => {
  return filters.value.genre !== 'all' || 
         filters.value.universe !== 'all' || 
         filters.value.language !== 'all' || 
         filters.value.country !== 'all' || 
         filters.value.ai !== 'all'
})

// 客户端筛选和排序
const filteredAndSortedMovies = computed(() => {
  let filtered = [...searchResults.value]

  // 应用筛选条件
  if (filters.value.genre !== 'all') {
    filtered = filtered.filter(movie => 
      movie.genres && movie.genres.includes(filters.value.genre)
    )
  }

  if (filters.value.universe !== 'all') {
    filtered = filtered.filter(movie => {
      if (Array.isArray(movie.universe)) {
        return movie.universe.includes(filters.value.universe)
      }
      return movie.universe === filters.value.universe
    })
  }

  if (filters.value.language !== 'all') {
    filtered = filtered.filter(movie => {
      if (Array.isArray(movie.language)) {
        return movie.language.includes(filters.value.language)
      }
      return movie.language === filters.value.language
    })
  }

  if (filters.value.country !== 'all') {
    filtered = filtered.filter(movie => {
      if (Array.isArray(movie.country)) {
        return movie.country.includes(filters.value.country)
      }
      return movie.country === filters.value.country
    })
  }

  if (filters.value.ai !== 'all') {
    const isAi = filters.value.ai === 'ai'
    filtered = filtered.filter(movie => movie.isAi === isAi)
  }

  // 应用排序
  filtered.sort((a, b) => {
    let result = 0
    switch (currentSort.value) {
      case 'views':
        result = (b.views || 0) - (a.views || 0)
        break
      case 'rating':
        result = (b.rating || 0) - (a.rating || 0)
        break
      case 'year':
        result = (b.year || 0) - (a.year || 0)
        break
      case 'updated_at':
        result = new Date(b.updatedAt || 0).getTime() - new Date(a.updatedAt || 0).getTime()
        break
      case 'relevance':
      default:
        // 相关度排序 - 保持原有顺序（搜索结果已经按相关度排序）
        result = 0
        break
    }
    return result
  })

  return filtered
})

const displayMovies = computed(() => {
  return filteredAndSortedMovies.value.slice(0, (currentPage.value + 1) * pageSize)
})

const hasMore = computed(() => {
  return displayMovies.value.length < filteredAndSortedMovies.value.length
})

// 方法
const handleFiltersUpdate = (newFilters: Record<string, string>) => {
  filters.value = {
    genre: newFilters.genre || 'all',
    universe: newFilters.universe || 'all',
    language: newFilters.language || 'all',
    country: newFilters.country || 'all',
    ai: newFilters.ai || 'all'
  }
  // 重置分页，但不重新加载数据
  currentPage.value = 0
}

const handleSortUpdate = (newSort: string) => {
  currentSort.value = newSort
  // 排序变化不需要重新加载数据，只需要重新排序
}

const clearFilters = () => {
  filters.value = {
    genre: 'all',
    universe: 'all',
    language: 'all',
    country: 'all',
    ai: 'all'
  }
  // 重置分页，但不重新加载数据
  currentPage.value = 0
}

const loadSearchResults = async () => {
  if (!searchQuery.value) return
  
  isInitialLoading.value = true
  try {
    // 加载更多数据以支持客户端筛选
    await performSearch(searchQuery.value, {
      genre: 'all',
      universe: 'all',
      language: 'all',
      country: 'all',
      ai: 'all'
    }, 'relevance', 0, 200) // 加载更多数据
  } catch (error) {
    console.error('Error loading search results:', error)
  } finally {
    isInitialLoading.value = false
  }
}

const loadMore = async () => {
  if (isSearching.value || !hasMore.value) return
  
  currentPage.value++
  // 客户端分页，不需要重新加载数据
}

// 监听搜索查询变化
watch(() => route.query.q, (newQuery) => {
  if (newQuery) {
    currentPage.value = 0
    // 重置筛选条件
    filters.value = {
      genre: 'all',
      universe: 'all',
      language: 'all',
      country: 'all',
      ai: 'all'
    }
    loadSearchResults()
  }
}, { immediate: true })

onMounted(() => {
  if (searchQuery.value) {
    loadSearchResults()
  }
})
</script> 